#Define python executable
PYTHON = python

#Compiler flags
CFLAGS = -std=c11 -O2 -Wall -Wextra

#Flags for things from the CakesFW ecosystem (Payload + ROP + bruh)
CAKEFLAGS = dir_out=$(CURDIR) name=rxTools.dat
BRUHFLAGS = $(CAKEFLAGS) filepath=/ APP_TITLE="rxTools Loader" APP_DESCRIPTION="Load rxTools from *hax payloads" APP_AUTHOR="WilliamO7"
ROPFLAGS = DATNAME=rxTools.dat GRAPHICS=../graphics/dsrop DISPNAME=rxTools

#Tools to build
tools = tools/addxor_tool tools/cfwtool tools/pack_tool tools/xor

#Stuff to put in data pack
DATA_FILES := $(wildcard data/*.*) rxmode/nat_patch.bin rxmode/agb_patch.bin rxmode/twl_patch.bin

.PHONY: all
all: rxTools.dat

.PHONY: distclean
distclean: clean
	@rm -rf release/rxTools.dat release/ninjhax release/mset

.PHONY: clean
clean:
	@make -C rxtools clean
	@make -C rxmode clean
	@make -C graphics/splash clean
	@make $(ROPFLAGS) -C CakesROP clean
	@make $(CAKEFLAGS) -C CakeHax clean
	make $(BRUHFLAGS) -C CakeBrah clean
	@rm -f $(tools) payload.bin data.bin rxTools.dat

.PHONY: release
release: rxTools.dat bruh msetrop
	@mkdir -p release/mset release/ninjhax/rxTools
	@cp rxTools.dat release
	@cp rxTools.3dsx release/ninjhax/rxTools/rxtools.3dsx
	@cp rxTools.smdh release/ninjhax/rxTools/rxtools.smdh
	@cp CakesROP/CakesROP.nds release/mset/rxinstaller.nds
	@cp CakesROP/CakesROPSpider/code.bin release/mset

.PHONY: rxTools.dat
rxTools.dat: rxtools/rxtools.bin rxmode/*.bin data.bin splash
	@make $(CAKEFLAGS) -C CakeHax bigpayload
	@dd if=rxtools/rxtools.bin of=$@ seek=160 conv=notrunc
	@dd if=data.bin of=$@ seek=2K conv=notrunc

.PHONY: bruh
bruh:
	make $(BRUHFLAGS) -C CakeBrah all

data.bin: tools/pack_tool
	@tools/pack_tool $(DATA_FILES) $@
	
splash:
	@cd graphics/splash && make
	@mv graphics/splash/*.bin data

msetrop:
	@$(MAKE) $(ROPFLAGS) -C CakesROP
	@$(MAKE) DATNAME=rxTools.dat -C CakesROP/CakesROPSpider

.PHONY: rxmode/*.bin
rxmode/*.bin: tools/cfwtool
	@cd rxmode && make

.PHONY: rxtools/rxtools.bin
rxtools/rxtools.bin: tools/addxor_tool
	@make -C $(dir $@) all
	@dd if=$@ of=$@ bs=896K count=1 conv=sync,notrunc

$(tools): tools/%: tools/toolsrc/%/main.c
	$(LINK.c) $(OUTPUT_OPTION) $^
